package com.topisv.tms.web.stock;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.service.stock.CusStockService;

@Controller
@RequestMapping(value = "/synStockForLKE")
public class SynStockForLKEController {

	@Autowired
	private CusStockService cusStockService;

	@RequestMapping(value = "")
	public String toSynStockForLKEPage() {
		return "stock/synStockForLKE";
	}
	
	/**
	 * 同步重量
	 * @param model
	 * @param request
	 * @param redirectAttributes
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "synStock")
	public String synStock(Model model, ServletRequest request,RedirectAttributes redirectAttributes) {
		
		try {
			
			HttpServletRequest httpRequest=(HttpServletRequest)request;
			
			httpRequest.setCharacterEncoding("UTF-8");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			List<FileItem> items = upload.parseRequest(httpRequest);
			Iterator<FileItem> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (!item.isFormField()) {
					if (item.getName() != null && !item.getName().equals("")) {
						
					    List<String[]> list = new ArrayList<String[]>(); 
					    Workbook rwb = null;
					     
					    //获取Excel文件对象
					    InputStream stream = item.getInputStream();
					    rwb = Workbook.getWorkbook(stream);
					    //获取文件的指定工作表 默认的第一个
					    Sheet sheet = rwb.getSheet(0);  
					    
					    for(int i=1; i<sheet.getRows(); i++){
					    	
					    	 Cell boxCodeCell=sheet.getCell(0,i);
					    	 Cell skuCell=sheet.getCell(1,i);
					    	 Cell salesNumCell=sheet.getCell(3,i);
					    	 Cell stockCodeCell=sheet.getCell(4,i);
					    	 
					         list.add( new String[]{boxCodeCell.getContents(), skuCell.getContents(), salesNumCell.getContents(), stockCodeCell.getContents()} );
					    }
					    
					    List<String[]> errorList=new ArrayList<String[]>();
					    List<String[]> rightList=new ArrayList<String[]>();
					    for (String[] ss : list) {
					    	
					    	String _boxCode=ss[0].trim();
					    	String _sku=ss[1].trim();
					    	String _salesNum=ss[2].trim();
					    	String _stockCode=ss[3].trim();
					    	
					    	if(_boxCode.equals("") || _sku.equals("") || _salesNum.equals("") || _stockCode.equals("")  ){
					    		errorList.add(new String[]{_boxCode,_sku,_salesNum,_stockCode});
					    		continue;
					    	}
					    	
					    	if(!isNum(_salesNum)){
					    		errorList.add(new String[]{_boxCode,_sku,_salesNum,_stockCode});
					    		continue;
					    	}
					    	
					    	rightList.add(new String[]{_boxCode,_sku,_salesNum,_stockCode});
						}
					    
					    stream.close();
					    this.cusStockService.synStockForLKE(rightList);
					    model.addAttribute("total",sheet.getRows());
					    model.addAttribute("rightList",rightList);
					    model.addAttribute("errorList",errorList);
					    model.addAttribute("message", "同步数据成功！");
						
					} else {
						model.addAttribute("message", "没有选择同步文件！");
					}
				}
			}
		}catch (Exception e) {
			
			model.addAttribute("message", "同步数据失败！");
		}
		return "stock/synStockFokLKE_result";
	}
	
	
	/**
	 * 导出模板
	 */
	@SuppressWarnings("deprecation")
	@RequestMapping(value = "updownExcel")
	public HttpServletResponse  updownExcel(ServletRequest request,ServletResponse response){
		
		HttpServletRequest httpRequest=(HttpServletRequest) request;
		HttpServletResponse httpResponse=(HttpServletResponse) response;
		
		try {
			
            // path是指欲下载的文件的路径。
			File file = new File(httpRequest.getRealPath("/")+"/WEB-INF/file/"+"MODEL-LKE-STOCK.xls");
            // 取得文件名。
            String filename = file.getName();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            
            //清空response
            httpResponse.reset();
            //设置response的Header
            httpResponse.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"),"ISO-8859-1"));
            httpResponse.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(httpResponse.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            
        } catch (IOException ex) {
            
        }
        return httpResponse;
	}
	
	/**
	 * 判断是否是数字
	 * @param str
	 * @return
	 */
	public  boolean isNum(String str){
		return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
	}
	
	
	
}